﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Diagnostics.Contracts;
using System.ComponentModel.Composition;

namespace Kooboo.Commerce.Repositories
{
    [Export(typeof(ICountryRepository))]
    public partial class EntityRepositories : ICountryRepository
    {
   

        public IQueryable<ICountry> Countries
        {
            get
            {
                return this.DataReaderContext.Countries;
            }
        }

        public void Post(ICountry country)
        {
            Contract.Requires(country != null);

            var item = new Country()
            {
                CountryCode = country.CountryCode,
                CountryName = country.CountryName
            };

            this.DataWriterContext.Countries.InsertOnSubmit(item);
            this.DataWriterContext.SubmitChanges();
        }

        public void Put(ICountry country)
        {
            Contract.Requires(country != null);

            var item = this.DataWriterContext.Countries
                .Where(i => i.CountryCode == country.CountryCode)
                .FirstOrDefault();

            if (item == null)
            {
                throw new KeyNotFoundException("Country:" + country.CountryCode);

            }

            item.CountryCode = country.CountryCode;
            item.CountryName = country.CountryName;

            this.DataWriterContext.SubmitChanges();
        }

        public void Delete(ICountry country)
        {
            if (country != null)
            {
                var item = this.DataWriterContext.Countries
                .Where(i => i.CountryCode == country.CountryCode)
                .FirstOrDefault();

                if (item != null)
                {
                    this.DataWriterContext.Countries.DeleteOnSubmit(item);
                    this.DataWriterContext.SubmitChanges();
                }
            }
        }

    }
}
